/**
 * Created by no1 on 2015/8/28.
 */
'use strict';
var mysql = require('../mysql.js');
var C = require('../../config/index');
var F = require('../../common/function');
var MPosts = require('../../model/posts.js');
var MTags = require('../../model/tags.js');
var MUser = require('../../model/users.js');
var Mman = require('../../common/man.js');
var imgRule = require('../../common/imgRule.js');
var _ = require('underscore');
var _s = require('underscore.string');
var md5 = require('md5');
var request = require('koa-request');
var async_request = require('request');
var logstash = require('./../logFlow/logstash.js');
_.v = require('validator');


/**
 * @todo API32 取轮播
 * @param Env
 * @returns {*}
 */
exports.getSlider = function*(Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  var position = fields.position;//分类 1发现页轮播 2 首页菜单 3 水印 4 通知
  var typeid = F.getSliderInfo(position).typeid;

  if (!_.v.isIn(parseInt(position), C.stid_arr)) {
    return F.returnMsg(400, '传递的参数错误', 1);
  }
  var key = C.redisPre.slider_list;
  key = _s.sprintf(key, parseInt(position));
  var temp = yield F.redisCo.EXISTS(key);

  if(temp==0)
  {//轮播缓存不存在
    var storeVal = '';
    var tmpSliderData = [];
    var order = 'ms.sort';
    var lastCreateDate = '';//水印最后创建日期，用于判断是否最新水印用
    if (position == 4) {
      order = 'ms.aid DESC'
    }
    if (typeid == 1 || typeid == 2 || typeid == 4) {//1:发现页轮播 2:首页菜单  4:通知 1:新发现轮播
      tmpSliderData = yield mysql.query("SELECT ms.aid,ms.type,ms.id,ms.begintime,ms.endtime,ms.timeline,ms.targeturl,ms.title FROM mh_slider ms WHERE ms.status=1 AND UNIX_TIMESTAMP() BETWEEN ms.begintime AND ms.endtime AND ms.sstype=? ORDER BY " + order, [position]);
    } else if (typeid == 3) {//水印
      tmpSliderData = yield mysql.query("SELECT ms.aid,mt.tagid,mt.tagimg,mt.tagtitle,mt.fix,mt.tagdesc,ms.begintime,ms.endtime,FROM_UNIXTIME(timeline, '%Y%m%d') as createdate FROM mh_tags mt INNER JOIN mh_slider ms ON tagid=ms.id WHERE mt.tagtype=3 AND ms.type=1 AND ms.sstype=? AND ms.`status`=1 ORDER BY " + order, [position]);
    }
    if (tmpSliderData && tmpSliderData.length > 0) {
      storeVal = JSON.stringify(tmpSliderData);
    } else {
      storeVal = JSON.stringify([]);
    }
    F.redisCo.SET(key, storeVal);//把轮播缓存
  }
  var sliderData = yield F.redisCo.GET(key);
  sliderData = JSON.parse(sliderData);
  //给最新水印创建日期赋值
  if (position == 3) {
    lastCreateDate = _.max(sliderData, function (oneData) {
      return oneData.createdate;
    }).createdate;
  }
  console.log(lastCreateDate);
  var returnData = [];
  var timeUnix = F.timestamp();
  if (sliderData.length > 0) {
    //var loginStatus = yield F.isLogin(Env);
    var j = 0;//当j为0时把当前id写入
    for (var i in sliderData) {
      if (parseInt(sliderData[i].begintime) <= timeUnix && timeUnix < parseInt(sliderData[i].endtime) + 86400) {
        if (typeid == 1 || typeid == 2 || typeid == 4) {//发现页/首页菜单/通知/新发现轮播
          if (position == 4 && j == 0 && loginStatus.status) {//把最后浏览的通知id写入用户信息表
            var uid = parseInt(loginStatus.uid);
            var userInfo = yield F.returnUserInfo(uid);
            userInfo = userInfo[0];
            var updateUserCache = {};
            if (sliderData[i].aid != parseInt(userInfo.lastnfid)) {//写入最后通知id
              updateUserCache.lastnfid = sliderData[i].aid;
              yield F.updateUserCache(uid, updateUserCache);//更新用户缓存
              mysql.query('UPDATE mh_user_info SET lastnfid=? WHERE uid=?', [sliderData[i].aid, uid]);
            }
          }
          var imgUrl = F.generateSliderUrl(sliderData[i].aid);
          var type = sliderData[i].type;
          var id = sliderData[i].id;
          var title = sliderData[i].title;
          var timeline = sliderData[i].timeline;
          if (position == 4 && (type == 3 || type == 5 || type == 7)) {//通知部分(3 帖子 5 url 7 H5)
            var uid = 2;
            var userInfo = yield F.returnUserInfo(uid);
            userInfo = userInfo[0];
            var nickName = '';
            var faceUrl = '';
            var vip = 0;
            var level = 0;
            var talent = '';
            var talentid = 0;
            var talent_level = 0;
            if (userInfo) {
              nickName = userInfo.nickname;
              faceUrl = F.generateFaceUrl(parseInt(userInfo.face), uid);
              vip = parseInt(userInfo.vip);
              var level = F.getLevelfromIntegral(userInfo.integral);
              level = level.lid;

              //显示达人称号
              //显示达人等级
              if (userInfo.talentid > 0 && vip == 0) {// 是否达人  (VIP 无达人属性)
                talent = F.getTalentInfo(userInfo.talentid).name;
                talent_level = level.talent_level; //  this.getTalentInfo(threads[i].talentid).talent_level;
              } else {
                talent = '';
                talentid = 0
              }
            }
          }
          switch (type) {
            case 1://标签
              returnData.push({aid: sliderData[i].aid, imgUrl: imgUrl, type: type, tagid: id});
              break;
            case 2://用户
              returnData.push({aid: sliderData[i].aid, imgUrl: imgUrl, type: type, uid: id});
              break;
            case 3://帖子
              if (position == 4) {
                var postData = yield mysql.queryOne('SELECT mp.pid,mt.imgcount,mp.imgext,mt.imagestring FROM mh_thread mt INNER JOIN mh_post mp ON mt.pid=mp.pid  WHERE mt.tid=?', [id]);
                var img = C.upyun.img_url + '/none.png';
                if (postData['imgcount'] > 0) {
                  //img = F.generateAttachmentUrl(postData['pid'], postData['imgext'], 1);
                  img=imgRule.str2imgURI(postData['imagestring'].split(',')[0])[0].imgURI + C.upyun.suffix_min;
                }
                returnData.push({
                  aid: sliderData[i].aid,
                  type: type,
                  faceUrl: faceUrl,
                  uid: uid,
                  nickname: nickName,
                  tid: id,
                  img: img,
                  title: title,
                  timeline: timeline,
                  vip: vip,
                  talent: talent,
                  talent_level: talent_level,
                  talentid: talentid,
                  imgUrl:imgUrl
                });
              } else {
                returnData.push({aid: sliderData[i].aid, imgUrl: imgUrl, type: type, tid: id});
              }
              break;
            case 4:// lbs
              returnData.push({aid: sliderData[i].aid, imgUrl: imgUrl, type: type, lbsid: id});
              break;
            case 5://url
              // 当版本 code<38 时，不显示
              //console.log(fields.app_ver_arr);
              if (fields.app_ver_arr && fields.app_ver_arr.code && fields.app_ver_arr.code>37){
              //if (1==1){
                if (position == 4) {
                  returnData.push({
                    aid: sliderData[i].aid,
                    type: type,
                    uid: uid,
                    faceUrl: faceUrl,
                    nickname: nickName,
                    targeturl: sliderData[i].targeturl,
                    title: title,
                    timeline: timeline,
                    vip: vip,
                    talent: talent,
                    talent_level: talent_level,
                    talentid: talentid,
                    imgUrl:imgUrl
                  });
                } else {
                  returnData.push({
                    aid: sliderData[i].aid,
                    imgUrl: imgUrl,
                    type: type,
                    targeturl: sliderData[i].targeturl,
                    title: title
                  });
                }
              }
              break;
            case 6://水印标签
              returnData.push({aid: sliderData[i].aid, imgUrl: imgUrl, type: type, tagid: id});
              break;
            case 7://H5
              var targetUrl = C.h5config.hurl + id + '.html';
              returnData.push({
                aid: sliderData[i].aid,
                type: 5,
                uid: uid,
                faceUrl: faceUrl,
                nickname: nickName,
                targeturl: targetUrl,
                title: title,
                timeline: timeline,
                vip: vip,
                talent: talent,
                talent_level: talent_level,
                talentid: talentid,
                imgUrl:imgUrl
              });
              break;
            default:
              break;
          }
        } else if (position == 3) {//水印
          //提取最后创建水印的日期，用于判断是否是最新水印
          //当传入more时，由第11条开始取
          if (fields.more && fields.more > 0 && j < 10) {
            j++;
            continue;
          }
          else if ((!fields.more || fields.more < 1) && j > 9) {
            break;
          }
          var tagUrl = F.generateTagUrl(sliderData[i].tagimg, sliderData[i].tagid, 2);
          var tagmarkUrl = F.generateTagMarkUrl(sliderData[i].tagid);
          var tagbannerUrl = F.generateTagBannerUrl(sliderData[i].tagid);
          returnData.push({
            tagurl: tagUrl,
            tagmarkurl: tagmarkUrl,
            tagbannerurl: tagbannerUrl,
            tagid: sliderData[i].tagid,
            tagtitle: sliderData[i].tagtitle,
            tagdesc: sliderData[i].tagdesc,
            fix: sliderData[i].fix,
            latest: sliderData[i].createdate == lastCreateDate ? 1 : 0
          });
        }
        j++;
      }
    }
    var data = {};
    data.items = returnData;
    if (position == 4 && loginStatus.status) {//4通知 登录状态下才返回登录者浏览的最后通知id
      data.newestaid = parseInt(userInfo.lastnfid);
    }
    if (data.items.length > 0) {
      return F.returnMsg(200, '成功', 3, data);
    } else {
      return F.returnMsg(300, '已没有数据了。', 1);
    }
  } else {
    return F.returnMsg(300, '已没有数据了。', 1);
  }

};
